package com.hantanger.weblog.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hantanger.weblog.model.Setting;
import com.hantanger.weblog.model.User;
import com.hantanger.weblog.util.HtmlUtil;

/**
 * 初始化
 * 
 * @author lys
 * 
 */
public class InitController extends BaseController {

	@Override
	public String doGet(HttpServletRequest request, HttpServletResponse response) {
		Setting setting = getSettingDao().getDefaultSetting();
		if (setting.isInit()) {
			try {
				response.sendRedirect("/");
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}
		return "init";
	}

	@Override
	public String doPost(HttpServletRequest request,
			HttpServletResponse response) {
		String email = HtmlUtil.getString(request, "email", "");
		String passwd = HtmlUtil.getString(request, "passwd", "");
		String repasswd = HtmlUtil.getString(request, "repasswd", "");
		String spaceUrl = HtmlUtil.getString(request, "spaceUrl", "");

		if (passwd.equals(repasswd)) {
			User user = new User();
			user.setEmail(email);
			user.setPassword(passwd);
			user.setPrivilege(User.PRIVILEGE_ADMIN);
			getUserDao().insert(user);
			if (user.getId() > 0) {
				Setting defaultSetting = getSettingDao().getDefaultSetting();
				defaultSetting.setInit(true);
				defaultSetting.setSpaceUrl(spaceUrl);
				getSettingDao().update(defaultSetting);
				try {
					response.sendRedirect("/");
				} catch (IOException e) {
					e.printStackTrace();
				}
				return null;
			}
		}
		return "init";
	}

}
